package com.lemeng.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.lemeng.dao.SpecMapper;
import com.lemeng.pojo.Spec;
import com.lemeng.service.SearchService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Autowired
    SpecMapper specMapper;

    @Override
    public Map<String, Object> search(Map<String, String> searchMap) {
        HashMap<String, Object> hashMap = new HashMap<>();

        //关键字搜索
        SearchRequest searchRequest = new SearchRequest("sku");
        searchRequest.types("doc");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        boolQueryBuilder.must(QueryBuilders.matchQuery("name",searchMap.get("keywords")));
        if (searchMap.containsKey("categoryName")){
            boolQueryBuilder.filter(QueryBuilders.termQuery("categoryName.keyword",searchMap.get("categoryName")));
        }
        if (searchMap.containsKey("brandName")){
            boolQueryBuilder.filter(QueryBuilders.termQuery("brandName.keyword",searchMap.get("brandName")));
        }
        if (searchMap.containsKey("price")){
            String price = searchMap.get("price");
            String[] split = price.split("-");
            int start=Integer.parseInt(split[0])*100;

            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(start));
            if (!"*".equals(split[1])) {
                int end=Integer.parseInt(split[1])*100;
                boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(end));
            }
        }

        for (String s : searchMap.keySet()) {
            if (s.contains("spec.")){
            boolQueryBuilder.filter(QueryBuilders.termQuery(s+".keyword",searchMap.get(s)));
            }
        }
        //添加查询
        searchSourceBuilder.query(boolQueryBuilder);

        //分页
        int size =5;
        int page=Integer.parseInt(searchMap.get("page"));


        int form = (page-1)*size;
        searchSourceBuilder.from(form).size(size);


        if (searchMap.containsKey("sort")){
            if (searchMap.get("sortOrder").equals("DESC")){
                searchSourceBuilder.sort(searchMap.get("sort"), SortOrder.DESC);
            }else {
                searchSourceBuilder.sort(searchMap.get("sort"),SortOrder.ASC);
            }
        }




        //添加聚合为了展示分类品牌
        searchSourceBuilder.aggregation(AggregationBuilders.terms("category_agg").field("categoryName.keyword"));

        searchSourceBuilder.aggregation(AggregationBuilders.terms("brand_agg").field("brandName.keyword"));



         searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            ArrayList<Map> list = new ArrayList<>();
            SearchHits hits = search.getHits();

            hashMap.put("total",hits.getTotalHits());

            for (SearchHit hit :hits.getHits()) {
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();

                sourceAsMap.put("id",hit.getId());

                list.add(sourceAsMap);
            }
            hashMap.put("skuList",list);

            //获取所有聚合
            Aggregations aggregations = search.getAggregations();
            //得到分类聚合
            ParsedStringTerms category_agg = aggregations.get("category_agg");
            ArrayList<String> categoryNames = new ArrayList<>();

            for (Terms.Bucket bucket : category_agg.getBuckets()) {
                categoryNames.add(bucket.getKeyAsString());
            }
            hashMap.put("categoryNames",categoryNames);
            //得到品牌的聚合
            ParsedStringTerms brand_agg = aggregations.get("brand_agg");
            ArrayList<String> brandNames = new ArrayList<>();
            for (Terms.Bucket bucket : brand_agg.getBuckets()) {
                brandNames.add(bucket.getKeyAsString());
            }
            hashMap.put("brandNames",brandNames);

            List<Spec> specs = new ArrayList<>();

            ArrayList<Map> list1 = new ArrayList<>();
            if (!CollectionUtils.isEmpty(categoryNames)) {
                specs = specMapper.selectByCatgoryNames(categoryNames);
                if (!CollectionUtils.isEmpty(specs)) {
                    for (Spec spec : specs) {
                        HashMap<String, Object> hashMap1 = new HashMap<>();
                        hashMap1.put("name",spec.getName());
                        hashMap1.put("value",spec.getOptions().split(","));
                        list1.add(hashMap1);
                    }
                }
            }
            hashMap.put("specsList",list1);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return hashMap;
    }

}
